﻿package com.edward.action;

import java.util.List;

import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import org.apache.struts2.ServletActionContext;
import org.springframework.security.annotation.Secured;
import org.springframework.security.context.SecurityContextHolder;
import org.springframework.security.userdetails.UserDetails;

import com.edward.JsonDateProcessor;
import com.edward.PagerModel;
import com.edward.model.Cargo;
import com.edward.model.DT_Cargo;
import com.edward.model.SaleList;
import com.edward.service.CargoManager;
import com.edward.service.DT_CargoManager;
import com.edward.service.SaleListManager;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class SaleListAction extends ActionSupport {


	private static final long serialVersionUID = 7298277870002100754L;

	private SaleListManager saleListManager;
	
	private DT_CargoManager dt_CargoManager;

	private CargoManager cargoManager;
	
	private SaleList saleList;
	
	private DT_Cargo dt_Cargo;
	
	private Cargo cargo;
	
	private int id;
	
	private int limit;
	
	private int start;
	
	private String query;
	
	private boolean oversea = false;


	public int getId() {
		return id;
	}


	public void setId(int id) {
		this.id = id;
	}


	public SaleList getSaleList() {
		return saleList;
	}


	public void setSaleList(SaleList saleList) {
		this.saleList = saleList;
	}


	public DT_Cargo getDt_Cargo() {
		return dt_Cargo;
	}


	public void setDt_Cargo(DT_Cargo dtCargo) {
		dt_Cargo = dtCargo;
	}


	public void setSaleListManager(SaleListManager saleListManager) {
		this.saleListManager = saleListManager;
	}


	public void setDt_CargoManager(DT_CargoManager dtCargoManager) {
		dt_CargoManager = dtCargoManager;
	}
	
	public Cargo getCargo() {
		return cargo;
	}


	public void setCargo(Cargo cargo) {
		this.cargo = cargo;
	}


	public void setCargoManager(CargoManager cargoManager) {
		this.cargoManager = cargoManager;
	}
	
	public int getLimit() {
		return limit;
	}


	public void setLimit(int limit) {
		this.limit = limit;
	}


	public int getStart() {
		return start;
	}


	public void setStart(int start) {
		this.start = start;
	}
	
	public boolean isOversea() {
		return oversea;
	}


	public void setOversea(boolean oversea) {
		this.oversea = oversea;
	}


	public String getQuery() {
		return query;
	}


	public void setQuery(String query) {
		this.query = query;
	}

	//添加saleList 的表头
	@Secured("ROLE_DEPOT_ADD")
	public String add() throws Exception{
		ActionContext ctx = ActionContext.getContext();        
		HttpServletResponse response = (HttpServletResponse)ctx.get(ServletActionContext.HTTP_RESPONSE);    
		response.setContentType("text/html;charset=UTF-8");
		saleList.setListNum(saleListManager.listNum());
		UserDetails userDetails = (UserDetails) SecurityContextHolder
		.getContext().getAuthentication().getPrincipal();
			saleList.setAuditor(saleListManager.getUserName(userDetails.getUsername()));
		saleListManager.addSaleList(saleList);
		int total = saleListManager.listSaleList(oversea).size();
		response.getWriter().print("{success : true , msg : '添加成功!',saleList_id:"+ saleList.getId()+",total:" + total + "}");
		return null;
	}
	
	@Secured("ROLE_DEPOT_UPDATE")
	public String update() throws Exception{
		ActionContext ctx = ActionContext.getContext();        
		HttpServletResponse response = (HttpServletResponse)ctx.get(ServletActionContext.HTTP_RESPONSE);    
		response.setContentType("text/html;charset=UTF-8");
		SaleList s = saleListManager.getSaleList(saleList.getId());
		saleList.setGoods(s.getGoods());
		saleList.setAuditor(s.getAuditor());
		saleListManager.updateSaleList(saleList);
		response.getWriter().print("{success : true , msg : '修改成功!'}");
		return null;
	}
	
	@Secured("ROLE_DEPOT_UPDATE")
	public String delete() throws Exception{
		ActionContext ctx = ActionContext.getContext();        
		HttpServletResponse response = (HttpServletResponse)ctx.get(ServletActionContext.HTTP_RESPONSE);    
		response.setContentType("text/html;charset=UTF-8");
		SaleList s = saleListManager.getSaleList(saleList.getId());
		if(s.getGoods().size() != 0){
			response.getWriter().print("{success : false , msg : '删除失败，存在销售货物列表，请先删除销售货物!'}");
		}else{
			saleListManager.deleteSaleList(s.getId());
			response.getWriter().print("{success : true , msg : '删除成功!'}");
		}
		return null;
	}

	@Secured("ROLE_DEPOT")
	public String getList() throws Exception {

		ActionContext ctx = ActionContext.getContext();        
		HttpServletResponse response = (HttpServletResponse)ctx.get(ServletActionContext.HTTP_RESPONSE);    
		response.setContentType("text/html;charset=UTF-8");
	    JsonConfig cfg = new JsonConfig();
		cfg.registerJsonValueProcessor(java.util.Date.class, new JsonDateProcessor());
		cfg.registerJsonValueProcessor(java.sql.Date.class, new JsonDateProcessor());
		PagerModel pager;
		pager = saleListManager.pagerList(start, limit,oversea);
		JSONObject jsonObject = JSONObject.fromObject(pager,cfg);
		String jsonStr = jsonObject.toString();
		response.getWriter().print(jsonStr);
		return null;
	}
	
	
	
	
	//添加saleList 的 货物明细
	@Secured("ROLE_DEPOT_ADD")
	public String addDTCargo() throws Exception{
		ActionContext ctx = ActionContext.getContext();        
		HttpServletResponse response = (HttpServletResponse)ctx.get(ServletActionContext.HTTP_RESPONSE);    
		response.setContentType("text/html;charset=UTF-8");
		SaleList s = saleListManager.getSaleList(saleList.getId());
		//判断列表中是否一存在该货物
		List <DT_Cargo>l  = s.getGoods();
		for (DT_Cargo dd : l) {
			if(dd.getCargo().getCode().equals(cargo.getCode())){
				response.getWriter().print("{success:false, msg : '添加失败，货物列表中以存在该货物'}");
				return null;
			}
			
		}
		cargo.setCount(dt_Cargo.getAmount());
		Cargo c = cargoManager.checkCargo(s.getWarehouse(), cargo.getCode());
		if(c.getCount()-cargo.getCount()<0){
			response.getWriter().print("{success:false, msg : '添加失败，此货物在该仓库中库存不足!'}");
			return null;
		}
		
		
		//如果销售方式等于 发运，在X库（在途库添加相应的货物）
		if(s.getType().equals("发运")){
			
			Cargo exist;
			Cargo x = new Cargo(c);
			if (x.getLocation().equals("A")||x.getLocation().equals("B")||x.getLocation().equals("C")){
				x.setLocation("X");
				x.setCount(dt_Cargo.getAmount());
				x.setId(0);
				//判断该库有没有对应货物
				 exist = cargoManager.checkCargo("X",x.getCode());
			}else{
				x.setLocation("Y");
				x.setCount(dt_Cargo.getAmount());
				x.setId(0);
				//判断该库有没有对应货物
				exist = cargoManager.checkCargo("Y",x.getCode());
			}
			if(exist == null){
				cargoManager.addCargo(x);
			}else{
				exist.setCount(exist.getCount() + dt_Cargo.getAmount());
				cargoManager.updateCargo(exist);
			}
		}
		
		c.setCount(c.getCount()-cargo.getCount());
		cargoManager.updateCargo(c);
		dt_Cargo.setCargo(c);
		dt_Cargo.setSum(dt_Cargo.getPrice() * dt_Cargo.getAmount());
		dt_CargoManager.addDT_Cargo(dt_Cargo);
		s.getGoods().add(dt_Cargo);
		saleListManager.updateSaleList(s);
		response.getWriter().print("{success : true , msg : '添加成功!'}");
		return null;
	}
	
	@Secured("ROLE_DEPOT_UPDATE")
	public String updateDTCargo() throws Exception {

		ActionContext ctx = ActionContext.getContext();        
		  HttpServletResponse response = (HttpServletResponse)ctx.get(ServletActionContext.HTTP_RESPONSE);    
		response.setContentType("text/html;charset=UTF-8");
		DT_Cargo dt = dt_CargoManager.getDT_Cargo(dt_Cargo.getId());
		
		//由于变更的cargo没有Id ,先从数据库中获取其ID 再一同更新
		Cargo c =dt.getCargo();
		int i = c.getCount() - dt_Cargo.getAmount() + dt.getAmount();
		if(i<0){
			response.getWriter().print("{success:false, msg : '添加失败，此货物在该仓库中库存不足!'}");
			return null;
		}
		
		//如果销售方式等于 发运，在X库（在途库更新相应的货物）
		SaleList s = saleListManager.getSL(dt_Cargo.getId());
		if(s.getType().equals("发运")){
			//判断该库有没有对应货物
			Cargo exist;
			if (c.getLocation().equals("A")||c.getLocation().equals("B")||c.getLocation().equals("C")){
				 exist = cargoManager.checkCargo("X",c.getCode());
			}else{
				exist = cargoManager.checkCargo("Y",c.getCode());
			}
			exist.setCount(exist.getCount() + dt_Cargo.getAmount() - dt.getAmount() );
			cargoManager.updateCargo(exist);
		}
		
		c.setCount(i);
		dt_Cargo.setCargo(c);
		dt_Cargo.setSum(dt_Cargo.getPrice() * dt_Cargo.getAmount());
		cargoManager.updateCargo(c);
		dt_CargoManager.updateDT_Cargo(dt_Cargo);
		response.getWriter().print("{success : true , msg : '修改成功!'}");
		return null;
	}
	
	@Secured("ROLE_DEPOT_UPDATE")
	public String deleteDTCargo() throws Exception {

		ActionContext ctx = ActionContext.getContext();        
		  HttpServletResponse response = (HttpServletResponse)ctx.get(ServletActionContext.HTTP_RESPONSE);    
		response.setContentType("text/html;charset=UTF-8");
		DT_Cargo dt = dt_CargoManager.getDT_Cargo(dt_Cargo.getId());
		Cargo c =dt.getCargo();
		c.setCount(c.getCount() + dt.getAmount() );
		//如果销售方式等于 发运，在X库（在途库更新相应的货物）
		SaleList s = saleListManager.getSL(dt_Cargo.getId());
		if(s.getType().equals("发运")){
			//判断该库有没有对应货物
			Cargo exist;
			if (c.getLocation().equals("A")||c.getLocation().equals("B")||c.getLocation().equals("C")){
			    exist = cargoManager.checkCargo("X",c.getCode());
			}else{
				exist = cargoManager.checkCargo("Y",c.getCode());
			}
			exist.setCount(exist.getCount() - dt.getAmount());
			cargoManager.updateCargo(exist);
		}
		
		cargoManager.updateCargo(c);
		dt_CargoManager.deleteDT_Cargo(dt_Cargo.getId());
		response.getWriter().print("{success : true , msg : '删除成功!'}");
		return null;
	}

	//获取grid 显示 的 分页信息
	@Secured("ROLE_DEPOT")
	public String getDTCargo() throws Exception {

		ActionContext ctx = ActionContext.getContext();        
		HttpServletResponse response = (HttpServletResponse)ctx.get(ServletActionContext.HTTP_RESPONSE);    
		response.setContentType("text/html;charset=UTF-8");
		JsonConfig cfg = new JsonConfig();
		cfg.registerJsonValueProcessor(java.util.Date.class, new JsonDateProcessor());
		cfg.registerJsonValueProcessor(java.sql.Date.class, new JsonDateProcessor());
		PagerModel pager;
	    pager = dt_CargoManager.pagerDTCargo(start, limit,saleList.getId());
		JSONObject jsonObject = JSONObject.fromObject(pager,cfg);
		String jsonStr = jsonObject.toString();
		response.getWriter().print(jsonStr);
		return null;
	}
	

	@Secured("ROLE_DEPOT")
	 public String getListJudge() throws Exception {
			ActionContext ctx = ActionContext.getContext();        
			HttpServletResponse response = (HttpServletResponse)ctx.get(ServletActionContext.HTTP_RESPONSE);    
			response.setContentType("text/html;charset=UTF-8");
				response.getWriter().print("{success : true , msg : '成功!',deny:false}");
		 return null;
	 }
	
	
	
	
	
}
